layui.config({
	base: '/static/plugin/build/js/'
}).use(['form', 'layer', 'layedit', 'ztree'], function() {
	var $ = layui.$;
	var form = layui.form;
	layer = layui.layer;
	layedit = layui.layedit;
	var editIndex;
	$(function() {
		//内容上方的工具栏
		loadDeptTree();
		editIndex = layedit.build('ancontent', {
			height: 160, //设置编辑器高度
			tool: ['strong', 'italic', 'underline', 'del', '|', 'left', 'center', 'right', 'link', 'unlink', 'face']
		});
	});
	//组织机构树初始化
	var setting = {
		check: {
			enable: true,
			chkboxType: {
				"Y": "s",
				"N": "ps"
			}
		},
		view: {
			dblClickExpand: false
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			beforeClick: deptTreeBeforeClick,
			onCheck: deptTreeOnCheck
		}
	};
	//加载组织机构树
	function loadDeptTree() {
		//查询组织机构
		$.get(
			"/mock/department.json",
			function(result) {
				if(result.code == 0) {
					var trees = result.data;
					trees.shift();
					for(var i = 0; i < trees.length; i++) {
						trees[i].open = false;
					}
					var zNodes = trees;
					$.fn.zTree.init($("#ztree"), setting, zNodes);
				}
			},
			"json"
		);

	}
	$("#deptNames").on("click", function() {
		ShowTreeMenu();
	});
	//展示组织机构树
	function ShowTreeMenu() {
		HidenTreeMenu();
		$("#deptMenuContent").slideDown("fast");
		$("body").bind("mousedown", TreeOnBodyDown);
	}
	//隐藏组织机构树
	function HidenTreeMenu() {
		$("#deptMenuContent").fadeOut("fast");
		$("body").unbind("mousedown", TreeOnBodyDown);
	}

	function TreeOnBodyDown(event) {
		if(!(event.target.id == "deptNames" || event.target.id == "deptMenuContent" || $(event.target).parents("#deptMenuContent").length > 0)) {
			HidenTreeMenu();
		}
	}

	function deptTreeBeforeClick(treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		zTree.checkNode(treeNode, !treeNode.checked, null, true);
		return false;
	}

	function deptTreeOnCheck(e, treeId, treeNode) {
		var zTree = $.fn.zTree.getZTreeObj("ztree");
		var nodes = zTree.getCheckedNodes(true);
		var deptIDs = "";
		var deptNames = "";
		for(var i = 0, l = nodes.length; i < l; i++) {
			deptNames += nodes[i].name + ",";
			deptIDs += nodes[i].id + ",";
		}
		if(deptNames.length > 0) deptNames = deptNames.substring(0, deptNames.length - 1);
		if(deptIDs.length > 0) deptIDs = deptIDs.substring(0, deptIDs.length - 1);
		var deptNameObj = $("#deptNames");
		deptNameObj.val(deptNames);
		var deptIDsObj = $("#deptIDs");
		deptIDsObj.val(deptIDs);
	}
});